package cn.xspace.wnx.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.xspace.android.xafcommon.base.BaseActivity;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.HypyUtil;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.T;
import com.xspace.android.xafcommon.view.dialog.ButtonClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.adapter.ContactListAdapter;
import cn.xspace.wnx.db.MyNewFriendDao;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.wnx.util.ForwardHelper;
import cn.xspace.wnx.util.Navigator;
import cn.xspace.wnx.view.QuickAlphabeticBar;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MyFriendActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = MyFriendActivity.class.getSimpleName();

    public static String SELECTED_MEMBERS = "SelectedMembery";

    private TitleBar mTitleBar;
    private RelativeLayout mRelativeSearch;
    private RelativeLayout mNewFriend;
    private ListView mListView;
    private QuickAlphabeticBar mQuicksearcht;
    private TextView mMsmCont;
    private TextView mTvUnReadCount;

    //只有转发时才不会为null,用到此变量
    private Bundle mBundle;
    private MsgRecordEntity recordEntity;

    private ArrayList<OrgDeptUserBean> mDataList;
    private ContactListAdapter mAdapter;
    private String userId;
    public static boolean refreshData = false;
    private TextView mTvSearch;

    public static boolean refreshUnreadCount = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (refreshData) {
            refreshData = false;
            requestNetWorkData();
        }
        if (refreshUnreadCount) {
            refreshUnreadCount = false;
            getMyFriendUnReadCount();
        }
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        mBundle = getIntent().getBundleExtra(BldNavigation.KEY_BUNDLER);
        if (mBundle != null) {
            recordEntity = (MsgRecordEntity) mBundle.getSerializable(MsgForwardActivity.FORWARD_ENTITY);
        }
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_my_friend);
    }

    @Override
    protected void initFindViewById() {
        mTitleBar = (TitleBar) findViewById(R.id.my_friend_titleBar);
        mTitleBar.showRightText();
        mTitleBar.setRightLayoutTextView(getResources().getString(R.string.add_friend));
        mTitleBar.setTitle(getResources().getString(R.string.my_friend));
        mRelativeSearch = (RelativeLayout) findViewById(R.id.relative_search);
        mTvSearch = (TextView) findViewById(R.id.edit_search);
        mTvSearch.setHint(R.string.search);
        mRelativeSearch.setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.lv_my_friend);
        mQuicksearcht = (QuickAlphabeticBar) findViewById(R.id.quicksearch_my_friend_list);
        mMsmCont = (TextView) findViewById(R.id.msm_cont_fast_position_my_friend);
        mQuicksearcht.init(mMsmCont);
        mQuicksearcht.setListView(mListView);

        LinearLayout headLayout = (LinearLayout) View.inflate(this, R.layout.list_view_header_my_friend, null);
        mNewFriend = (RelativeLayout) headLayout.findViewById(R.id.rl_new_friends);
        mNewFriend.setOnClickListener(this);
        mTvUnReadCount = (TextView) headLayout.findViewById(R.id.tv_friend_count);

        mListView.addHeaderView(headLayout);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mQuicksearcht.setHight(mQuicksearcht.getHeight());
                mQuicksearcht.setVisibility(View.VISIBLE);
            }
        }, 500);
        if (recordEntity != null) {
            mNewFriend.setVisibility(View.GONE);
            mTitleBar.setRightLayoutVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        userId = MyInfoUtil.getMyUserid(mContext);
        mDataList = new ArrayList<>();
        mAdapter = new ContactListAdapter(mContext, mDataList, mQuicksearcht, false);
        mListView.setAdapter(mAdapter);
        requestNetWorkData();
        getMyFriendUnReadCount();
    }

    private void requestNetWorkData() {
        showWaitDialog();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("user_id", userId);
        OkHttpManager.getInstance().commonRequest(Constants.QUERY_FRIENDS, requestMap)
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseReturnBean, List<OrgDeptUserBean>>() {
                    @Override
                    public List<OrgDeptUserBean> call(BaseReturnBean baseReturnBean) {
                        List<OrgDeptUserBean> dataList = new ArrayList<>();
                        try {
                            JSONArray jsonArray = new JSONArray(baseReturnBean.data);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                OrgDeptUserBean bean = new OrgDeptUserBean();
                                JSONObject single = jsonArray.getJSONObject(i);
                                bean.user_id = single.optString("user_id");
                                bean.user_name = single.optString("user_name");
                                bean.user_logo = single.optString("user_logo");
                                bean.dept_id = single.optString("dept_id");
                                bean.dept_name = single.optString("dept_name");
                                bean.org_id = single.optString("org_id");
                                bean.org_name = single.optString("org_name");
                                bean.user_sex = single.optString("user_sex");
                                bean.user_status = single.optInt("user_status");
                                bean.shotKey = HypyUtil.cn2py(bean.user_name);
                                bean.is_stop = single.optString("is_stop");
                                dataList.add(bean);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        return dataList;
                    }
                })
                .doOnNext(new Action1<List<OrgDeptUserBean>>() {
                    @Override
                    public void call(List<OrgDeptUserBean> newList) {
                        if (newList.size() != 0) {
                            for (OrgDeptUserBean bean : newList) {
                                bean.shotKey = HypyUtil.cn2py(bean.user_name);
                            }
                            Collections.sort(newList, new Comparator<OrgDeptUserBean>() {
                                @Override
                                public int compare(OrgDeptUserBean lhs, OrgDeptUserBean rhs) {
                                    if (TextUtils.isEmpty(lhs.shotKey)) {
                                        return -1;
                                    }
                                    String key1 = lhs.shotKey.toUpperCase();
                                    Integer num1 = HypyUtil.chartSortMap.get(key1);
                                    String key2 = rhs.shotKey.toUpperCase();
                                    Integer num2 = HypyUtil.chartSortMap.get(key2);
                                    if (num1 == null) {
                                        return -1;
                                    }
                                    if (num2 == null) {
                                        return 1;
                                    }
                                    return num1.compareTo(num2);
                                }
                            });
                        }

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OrgDeptUserBean>>() {
                    @Override
                    public void onCompleted() {
                        LogUtil.d(TAG, "onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        e.printStackTrace();
                        T.showShort(mContext, e.getMessage());
                    }

                    @Override
                    public void onNext(List<OrgDeptUserBean> newList) {
                        hideWaitDialog();
                        mDataList.clear();
                        mDataList.addAll(newList);
                        mAdapter.initAlpha(mDataList);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }

//    private void getLocalData() {
//        for (int i = 0; i < 10; i++) {
//            OrgDeptUserBean orgDeptUserBean = new OrgDeptUserBean();
//            orgDeptUserBean.user_name = "员工" + i;
//            orgDeptUserBean.shotKey = i + "";
//            mDataList.add(orgDeptUserBean);
//        }
//        mAdapter.initAlpha(mDataList);
//        mAdapter.notifyDataSetChanged();
//    }

    @Override
    protected void initEvent() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    final OrgDeptUserBean bean = mDataList.get(position - mListView.getHeaderViewsCount());
                    LogUtil.d(TAG, "wubaojie>>>" + "onItemClick: Position :" + position);
                    if (forward(bean)) return;
                    String userId = bean.user_id;
                    Navigator.startPersonCardActivity(mContext, userId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        mTitleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SearchForAddFriendActivity.class);
                startActivity(intent);
            }
        });
    }

    private boolean forward(final OrgDeptUserBean bean) {
        if (recordEntity != null) { //转发时会弹出转发确认对话框
            if (TextUtils.equals(MyInfoUtil.getMyUserid(mContext), bean.user_id)) {
                T.showShort(mContext, R.string.cant_forward_toself);
                return true;
            }
            ForwardHelper.getInstance().confirmBeforeForward(mContext, new ButtonClickListener() {
                        @Override
                        public void buttonClick(View view) {
                            LogUtil.d("确认");
                            ForwardHelper.getInstance().sendMessageRecordSingleChat(mContext,
                                    recordEntity, bean);
                            Map<String, Object> fmap = new HashMap<>();
                            fmap.put(EventBusConstant.TYPE, EventBusConstant.FINISH_PAGE_FORWARD);
                            EventBus.getDefault().post(fmap);
                        }
                    },
                    recordEntity,
                    bean.user_name);
            //转发到此结束
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.relative_search) { //搜索
            Intent mIntent = new Intent(this, UserSearchResultActivity.class);
            if (mBundle == null) {
                mBundle = new Bundle();
            }
            mBundle.putString(BldNavigation.SEARCH_TYPE, BldNavigation.SEARCH_MY_FRIEND);
            mBundle.putSerializable(SELECTED_MEMBERS, mDataList);
            mIntent.putExtra(BldNavigation.KEY_BUNDLER, mBundle);
            startActivity(mIntent);
        } else if (v.getId() == R.id.rl_new_friends) { //好友申请列表
            Intent mIntent = new Intent(this, NewFriendActivity.class);
            startActivity(mIntent);
        }
    }

    private void getMyFriendUnReadCount() {
        int unReadCount = MyNewFriendDao.getInstance().getUnReadCount();
        if (unReadCount > 0) {
            mTvUnReadCount.setText(unReadCount + "");
            mTvUnReadCount.setVisibility(View.VISIBLE);
        } else {
            mTvUnReadCount.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onEventMainThread(Map<String, Object> inParam) {
        if (EventBusConstant.NEW_FRIEND_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            if (EventBusConstant.NEW_FRIEND_FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                requestNetWorkData();
            }
            if (EventBusConstant.NEW_FRIEND_PUSH_BEAN.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                getMyFriendUnReadCount();
            }
        } else if (EventBusConstant.DELETE_FRIEND_PUSH.equals(inParam.get(EventBusConstant.TYPE))) {
            if (EventBusConstant.DELETE_FRIEND_FINISH.equals(inParam.get(EventBusConstant.ACTION_KEY))) {
                //好友关系解除,刷新好友列表
//                requestNetWorkData();
                String friend_id = (String) inParam.get(EventBusConstant.ACTION_VALUE);
                for (OrgDeptUserBean orgDeptUserBean : mDataList) {
                    if (orgDeptUserBean.user_id.equals(friend_id)) {
                        mDataList.remove(orgDeptUserBean);
                        break;
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
